﻿using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.Management;
using System.Windows;
using MMC20;

namespace ServiceComparer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        ObservableCollection<ServiceItem> itemList = new ObservableCollection<ServiceItem>();
        ObservableCollection<ServiceItem> currentItemList = new ObservableCollection<ServiceItem>();

        private string ObjToStr(object obj)
        {
            if (obj == null)
                return "";
            else
                return obj.ToString();            
        }

        MMC20.Application appObj = new MMC20.Application();
        MMC20.View objView = null;
        MMC20.Nodes objList = null;
        private void loadMMC20()
        {
            appObj.Load("services.msc");
           
            objView = appObj.Document.ActiveView;
            objList = objView.ListItems;
        }
        private void unloadMMC20()
        {
            appObj.Quit();
            objView = null;
            objList = null;
        }
        private void OpenServiceProperty(string serviceName)
        {
            foreach (Node n in objList)
            {
                if (n.Name == serviceName)
                {
                    objView.Select(n);
                    objView.DisplaySelectionPropertySheet();
                    break;
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            loadMMC20();
                //appObj.Show();
                // Get the WMI class
                //ManagementClass c = new ManagementClass(
                //    new ManagementPath("Win32_Service"));


                //// Get the methods in the class
                //MethodDataCollection methods =
                //    c.Methods;

                //// display the methods
                //Console.WriteLine("Method Names: ");
                //foreach (MethodData method in methods)
                //{
                //    Console.WriteLine(method.Name);
                //}
                //Console.WriteLine();

                // Get the properties in the class
                //PropertyDataCollection properties =
                //    c.Properties;

                //// display the properties
                //Console.WriteLine("Property Names: ");
                //foreach (PropertyData property in properties)
                //{
                //    Console.WriteLine(property.Name + ":" + property.Value);
                //}
                //Console.WriteLine();

                //// Get the Qualifiers in the class
                //QualifierDataCollection qualifiers =
                //    c.Qualifiers;

                //// display the qualifiers
                //Console.WriteLine("Qualifier Names: ");
                //foreach (QualifierData qualifier in qualifiers)
                //{
                //    Console.WriteLine(qualifier.Name);
                //}


                ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Service");

            foreach (ManagementObject service in mos.Get())
            {
                string DisplayName = ObjToStr(service["DisplayName"]);
                string Name = ObjToStr(service["Name"]);
                string Caption = ObjToStr(service["Caption"]);
                string Description = ObjToStr(service["Description"]);
                string Started = ObjToStr(service["Started"]);
                string Status = ObjToStr(service["Status"]);
                string StartMode = ObjToStr(service["StartMode"]);
                string PathName = ObjToStr(service["PathName"]);
                //string InstallDate = ObjToStr(((DateTime)service["InstallDate"]).ToString("yyyyMMdd HH:mm:ss"));




                ServiceItem si = new ServiceItem(DisplayName, Name, Description, Started.Equals("True") ? "正在运行":"" , StartMode, "", PathName);
                itemList.Add(si);
            }


            listView.ItemsSource = itemList;
            foreach(ServiceItem si in itemList)
            {
                currentItemList.Add(si.Clone());
            }

        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfDlg = new SaveFileDialog();
            sfDlg.Filter = "快照文件(*.xml)|*.xml";
            if(sfDlg.ShowDialog() == true)
            {
                SerializerManager.serialize_to_xml(sfDlg.FileName, itemList);
                MessageBox.Show("保存成功！");
            }
        }

        private void OnCompareFile(object sender, RoutedEventArgs e)
        {
            if (MenuCompareFile.Header.Equals("取消对比(_C)"))
            {
                MenuCompareFile.Header = "对比快照(_S)";
                itemList.Clear();
                
                foreach (ServiceItem si in currentItemList)
                {
                    itemList.Add(si.Clone());
                }
                
            }
            else
            {
              
                OpenFileDialog ofDlg = new OpenFileDialog();
                ofDlg.Filter = "快照文件(*.xml)|*.xml";
                if (ofDlg.ShowDialog() == true)
                {
                    ObservableCollection<ServiceItem> list = (ObservableCollection<ServiceItem>)SerializerManager.deserialize_from_xml(ofDlg.FileName, typeof(ObservableCollection<ServiceItem>));

                    for (int i = 0; i < itemList.Count; i++)
                    {
                        itemList[i].Compare = 1;
                    }
                    for (int i = 0; i < list.Count; i++)
                    {
                        bool bFind = false;
                        for (int j = 0; j < itemList.Count; j++)
                        {
                            if (itemList[j].Name == list[i].Name)
                            {
                                bFind = true;
                                itemList[j].Compare = 0;
                                break;
                            }
                        }
                        if (!bFind)
                        {
                            list[i].Compare = 2;
                            itemList.Add(list[i]);
                        }
                    }
                    listView.ItemsSource = currentItemList;
                    listView.ItemsSource = itemList;
                    MenuCompareFile.Header = "取消对比(_C)";
                  
                }
            }
        }

        private void OnExit(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void OnItemDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ServiceItem selectItem = (ServiceItem)listView.SelectedItem;
            if (selectItem != null && selectItem.Compare != 2)
                OpenServiceProperty(selectItem.DisplayName);
        }

        private void OnWindowClosed(object sender, EventArgs e)
        {
            unloadMMC20();
        }
    }
}
